package main

import (
	"context"
	"github.com/gin-gonic/gin"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func main() {
	r := gin.Default()

	clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
	client, err := mongo.Connect(context.TODO(), clientOptions)
	if err != nil {
		panic(err.Error())
	}

	defer func() {
		if err = client.Disconnect(context.TODO()); err != nil {
			panic(err)
		}
	}()

	studentCourse := client.Database("user201800301137").Collection("student_course")

	r.GET("/getMyCourse", func(c *gin.Context) {
		sid := c.Query("sid")
		if sid == "" {
			c.JSON(200, gin.H{
				"code":    -1,
				"message": "参数异常",
			})
			return
		}

		filter := bson.M{
			"sid": sid,
		}

		cursor, err := studentCourse.Find(context.TODO(), filter)
		if err != nil {
			c.JSON(200, gin.H{
				"code":    -1,
				"message": "数据库异常",
			})
			return
		}

		var results []bson.M
		if err = cursor.All(context.TODO(), &results); err != nil {
			c.JSON(200, gin.H{
				"code":    -1,
				"message": "查询失败",
			})
		}

		c.JSON(200, gin.H{
			"code":    0,
			"message": "查询成功",
			"data":    results,
		})
	})

	_ = r.Run()
}
